import {
	getdetail,
	groupBuy,
	personalBuy,
	getUserCouponsList,
	personalTakeRedPackage,
	personalRefundPledgeMoney,
	goodsSpecsInfo
} from '../../../../../api/shopping/shopping.js'
import {
	navigateTo,
	getKey
} from '../../../common/js/util.js'
import {
	mapState
} from 'vuex';
export default {
	data() {
		return {
			redList: [],
			zf_num: null,
			type: "",
			pay_pledge_money_type: 1,
			IS_WEIXIN: false,
		}
	},
	computed: {
		...mapState(['hasRegister', 'userinfo'])
	},
	onLoad(e) {
		//#ifdef MP-WEIXIN
		this.IS_WEIXIN = true;
		//#endif
	},
	methods: {
		toPlay() {
			if (this.value.length == 0) {
				uni.showToast({
					title: '请阅读并同意协议',
					icon: 'none'
				});
			} else {
				//#ifdef MP-WEIXIN
				wx.requestSubscribeMessage({
					tmplIds: ['B_7joSEN46W2ASK_FFLlS1BZ6gcYpAGOO7QWR6FIkh4',
						'qjx1cFCcC-VgTBYqA1X8Jz0GseoRAT13EtFPdQi_uvA',
						'zgyC1pGPyy439l8hRXliYRtUoTPVGN2i_R1sjmrVoyg'
					],
					complete: () => {
						//#endif
						switch (this.buyType) {
							case 1:
								this.closePop();
								this.personalBuy();
								break;
							case 2:
								this.closePop();
								this.groupBuy();
								break;
							case 3:
								this.closePop();
								this.groupBuy();
								break;
							default:
								break;
						}
						//#ifdef MP-WEIXIN
					}
				})
				//#endif
			}
		},

		randomGift(j) {
			let random = Math.floor(Math.random() * 10)
			if (random < this.redList.length && random != j) {
				this.$set(this.redList[random], 'backUrl', this.IMGLink + '/shopping/shadowgift.png')
			} else {
				this.randomGift(j);
			}
		},
		async choseLucky(i, j) {
			this.enbaleReward = false;
			const res = await personalTakeRedPackage({
				goods_id: this.info.id
			})
			if (res.data) {
				this.$store.dispatch("updateUserInfo")
				if (res.data.is_win == 1) {
					this.serial_num = res.data.serial_num;
					this.$set(this.redList[j], 'backUrl', this.IMGLink + '/shopping/gift.png');
					setTimeout(() => {
						this.rewardBtnText = '去支付';
					}, 500)
					this.rewardBackText = '稍后支付>';
				} else {
					this.$set(this.redList[j], 'backUrl', this.IMGLink + '/shopping/redbag.png')
					this.$set(this.redList[j], 'money', res.data.redpackage)
					this.randomGift(j);
					if (res.data.is_new_user == 1) {
						this.rewardBtnText = '去领取新人福利';
						this.rewardBackText = '';
						this.closeReward(1);
					} else {
						setTimeout(() => {
							this.rewardBtnText = '再来一次';
						}, 500)
						this.rewardBackText = '退还保证金>'
					}
				}
				for (let n of this.redList) {
					n.class = 'animat red_box';
				}
			}
		},
		backMoney() {
			this.getdetail();
			if (this.rewardBackText == '退还保证金>') {
				this.$refs.refusepop.open('center');
			} else {
				this.$refs.singlepop.close()
			}
		},
		rewardBtn() {
			if (this.rewardBtnText == '再来一次') {
				this.redList.length = 0;
				this.redList = [];
				for (let i = 0; i < this.info.people_number; i++) {
					let item = {
						url: this.IMGLink + '/shopping/luckybag.png',
						backUrl: this.IMGLink + '/shopping/shadowbag.png',
						class: 'red_box animatreseve'
					}
					this.redList.push(item)
				}
				this.enbaleReward = true;
				this.rewardBtnText = '';
			} else if (this.rewardBtnText == '去领取新人福利') {
				uni.reLaunch({
					url: '/pages/index/newcomer-mission/newcomer-mission',
				});
			} else if (this.rewardBtnText == '去支付') {
				this.enbaleReward = true;
				this.closeSingle();
				navigateTo(`/pagesA/my/orders/orderDetail?serial_num=${this.serial_num}`)
			}
		},
		groupBuy() {
			const ids = this.buyInfo().ids;
			const count = this.buyInfo().count;
			let type = this.IS_WEIXIN ? 1 : 2;
			let url = '';
			// #ifdef H5
			url = location.href;
			if (getKey('type', 'index?')) {
				url = url.split('-type')[0];
			}
			// #endif

			// 支付端 1小程序（默认） 2 H5
			groupBuy({
				goods_id: this.id,
				topic_id: this.topic_id,
				type: this.playId,
				pay_pledge_money_type: this.pay_pledge_money_type,
				goods_specs_content: ids,
				custom_number: count,
				pay_pledge_money_coupon_id: this.couponId,
				zf_num: this.zf_num,
				pay_channel: type,
				return_url: url ? url.replace(/\&/g, '-') + '-type=2' : ''
			}).then(res => {
				this.$store.dispatch("updateUserInfo")
				const data = res.data;
				this.rank = data.groupCount;
				this.manyLast = false;
				if (this.rank == this.info.people_number) {
					this.manyLast = true;
				}
				if (data.is_win == 1) {
					this.sucessMany = '中奖';
					this.sucessManyBtn = '去支付';
					this.serialNum = data.serial_num;
				} else {
					this.sucessMany = '获得红包'
					this.sucessManyBtn = '去查看'
				}
				this.$refs.manypop.open('center');
				this.pay_pledge_money_type = 1;
				this.zf_num = null;
				this.initPay();
				this.getdetail();
			}).catch(err => {
				if (err.code == -109) {
					this.zf_num = err.data.zf_num;
					if (err.data.payUrl && !this.type) {
						// #ifdef MP-WEIXIN
						navigateTo(
							`/pages/pay/pay-webview?payUrl=${encodeURIComponent(err.data.payUrl)}&type=1`)
						this.finsh();
						// #endif
						// #ifdef H5
						location.href = err.data.payUrl;
						// #endif
					}
				} else {
					this.initPay();
				}
			});
		},
		personalBuy() {
			const ids = this.buyInfo().ids;
			const count = this.buyInfo().count;
			let type = this.IS_WEIXIN ? 1 : 2;
			let url = '';
			// #ifdef H5
			url = location.href;
			if (getKey('type', 'index?')) {
				url = url.split('-type')[0];
			}
			// #endif
			// debugger
			personalBuy({
					goods_id: this.id,
					topic_id: this.topic_id,
					goods_specs_content: ids,
					pay_pledge_money_coupon_id: this.couponId,
					pay_pledge_money_type: this.pay_pledge_money_type,
					zf_num: this.zf_num,
					pay_channel: type,
					return_url: url ? url.replace(/\&/g, '-') + '-type=2' : ''
				})
				.then(res => {
					if (res.code == 200) {
						this.$store.dispatch("updateUserInfo")
						this.$refs.singlepop.open('center');
						this.pay_pledge_money_type = 1;
						this.zf_num = null;
						// this.getdetail();
						this.initPay();
					}
				})
				.catch((err) => {
					if (err.code == -109) {
						this.zf_num = err.data.zf_num;
						if (err.data.payUrl && !this.type) {
							// #ifdef MP-WEIXIN
							navigateTo(
								`/pages/pay/pay-webview?payUrl=${encodeURIComponent(err.data.payUrl)}&type=2`)
							this.finsh();
							// #endif
							// #ifdef H5
							location.href = err.data.payUrl;
							// #endif
						}
					} else {
						this.initPay();
					}
				});
		},
		initPay() {
			this.zf_num = null;
			this.pay_pledge_money_type = null;
			this.payFlag = false
		},
		finsh() {
			uni.$once('finsh', (data) => {
				if (this.zf_num) {
					if (data.status == 'success' && data.type == 2) {
						this.pay_pledge_money_type = 2;
						this.personalBuy();
					} else if (data.status == 'success' && data.type == 1) {
						this.pay_pledge_money_type = 2;
						this.groupBuy();
					}
				}
			})
		},
		buyInfo() {
			let ids = '';
			this.specifitionIds.map((i, j) => {
				j == this.specifitionIds.length - 1 ? ids += `${i.id}_${i.list.id}` : ids +=
					`${i.id}_${i.list.id}-`;
			})
			let count = 0;
			if (this.playId == 2) {
				count = this.playList[1].count;
			}
			return {
				ids,
				count
			}
		},
		choseType(data) {
			if (this.couponId && data != 2) {
				this.$Toast.none('免保证金只能用于单次拼购');
				return false;
			}
			for (let i of this.playList) {
				i.active = false
			}
			this.playList[data].active = true;
			this.playId = this.playList[data].id;
		},
		choseActive(j, index) {
			for (let n of this.info.goods_specs_list[j].attr_values) {
				n.active = false;
			}
			let item = {
				id: this.info.goods_specs_list[j].id,
				list: {
					...this.info.goods_specs_list[j].attr_values[index]
				}
			}
			this.specifitionIds[j] = {
				...item
			};
			this.specifitionText = '';
			this.specifitionIds.map((i) => {
				this.specifitionText += i.list.attr_value
			})
			this.info.goods_specs_list[j].attr_values[index].active = true;
			this.goodsSpecsInfo();
		},
		async goodsSpecsInfo() {
			const res = await goodsSpecsInfo({
				goods_id: this.info.id,
				goods_specs_content: this.buyInfo().ids,
				group_type: this.buyType == 3 ? 2 : this.buyType
			});
			if (res) {
				res.data.is_stock == 0 ? this.is_stock = true : this.is_stock = false;
				this.choseinfo = Object.assign({}, res.data)
			}
		},

	}
}
